import { createRouter, createWebHashHistory } from 'vue-router'
import Router from 'vue-router'
import { getRouter } from "@/utils/storage";
import { filterRoute } from "@/utils/setting";
import layout from '@/views/layout/LayoutIndex'
/**
 * 关于路由解释如下：
 * Note: 显示二级菜单当且仅当路由 children>1
 *
 * hidden: true                   当设置 true 的时候该路由不会在侧边栏出现 如401，login等页面，或者如一些编辑页面/edit/1
 * meta: {}                       路由参数
 * component: Layout              作为所有菜单路由的视图出口 包括(header , sidebar , Main)
 */

const routes = [
  {
    path: '/',
    name: 'index',
    component: layout,
    children: [],
    meta: {
      title: '首页'
    }
  },
  {
    path: "/:catchAll(.*)",
    component: () => import("@/views/error/Error.vue"),
    meta: {
      title: '404',
    },
  },
  {
    path: "/VRLocPreview",
    name: 'VRPreview',
    component: () => import("@/views/content/VR/VRPreview.vue"),
  }
]

const router = createRouter({
  // 后端刷新问题,使用hash路由
  history: createWebHashHistory(),
  routes
})


router.dynamicRoutes = (routes) => {
  resetRouter()
  routes = routes ? routes : getRouter()
  routes = routes && routes.length && routes.length > 0 ? routes : []
  routes.forEach(route => {
    // 更新options
    // 重写component
    route = filterRoute(route)
    router.options.routes.find(item => item.name === 'index').children.push(route)
    //添加到index下
    router.addRoute('index',route)
  })
}

//重置路由（默认只含首页大屏和登录）
export function resetRouter() {
  // const newRouter = router
  // router.matcher = newRouter.matcher
  const createRouter = () => {
    new Router({
      mode: 'hash',
      base: process.env.BASE_URL,
      routes: router
    })
  }
  router.matcher = createRouter.matcher
}

router.dynamicRoutes()

export default router
